/**
 * 
 */
package aiproject3.models;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Chris Smith
 *
 */
public class MajorityModel extends Model<Character, Integer> {

	/**
	 * The highest ranked character in this model (in terms of frequency)
	 */
	private Character _currentPrediction;
	
	private MajorityModel() {
		super();
		_currentPrediction = null;
	}
	
	public static MajorityModel createMajorityModel(String trainingFile) {	
		try {
			File file = new File(trainingFile);
			if (!file.exists()) {
				System.out.println("Error: Unable to train model... Training file not found.");
			} else {
				MajorityModel model = new MajorityModel();
				
				FileInputStream fstream = new FileInputStream(file);
			    DataInputStream in = new DataInputStream(fstream);
			    BufferedReader br = new BufferedReader(new InputStreamReader(in));
			    
			    String strLine;
			    
			    while ((strLine = br.readLine()) != null) {
		    		// Break up input-string into 'array' of elements
		    		String[] row = strLine.split("\\s*,\\s*");
		    		for (String unit : row) {
		    			if (unit.length() != 1) {
		    				System.out.println("Error: Malformed input in training file... Expecting a single character.");
		    				return null;
		    			} else 
		    				model.addToModel(unit.charAt(0));
		    		}
			    }
			    in.close();
			    return model;
			}
		} catch (IOException ex) {
			System.out.println("Error: Unable to access training file... \n" + ex.getMessage());
		}
		return null;
	}

	@Override
	public void addToModel(Character unit) {
		if (_currentPrediction == null)
			_currentPrediction = unit;
		
		if (_data.containsKey(unit)) {
			if (_data.get(unit) >= _data.get(_currentPrediction))
				_currentPrediction = unit;
			_data.put(unit, _data.get(unit) + 1);
		} else {
			_data.put(unit, 1);
		}
	}

	@Override
	public Character predictNext() {
		return _currentPrediction;
	}	
	
}
